﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Input;
using System.IO;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using ViewMaker.Core.Controls;
using ViewMaker.Core.Utils;

namespace ViewMaker.Core.ViewModels
{
    [View(ViewControlType.Grid)]
    [ViewProperty(GridViewControl.Properties.Margin, "10")]
#if !SILVERLIGHT
    [ViewProperty(GridViewControl.Properties.WindowResizeMode, System.Windows.ResizeMode.NoResize)]
#endif
    [ViewProperty(GridViewControl.Properties.LoadCommand, "BeginCommand")]
    [ViewProperty(GridViewControl.Properties.UnloadCommand, "CancelCommand")]
    public class DataEditViewModel<T> : ViewModelBase, IViewLayoutGeneratorProvider where T : IEditableObject
    {
        private const int buttonWidth = 60;

        private bool editing = false;

        [Browsable(true)]
        public T Data { get; set; }

        [Browsable(false)]
        public ICommand BeginCommand { get { return CreateCommand(Begin); } }
        private void Begin()
        {
            Data.BeginEdit();
            editing = true;
        }

        [Display(Name="OK",Order=1)]
        [ViewProperty(ButtonViewControl.Properties.Width, buttonWidth)]
        public ICommand OkCommand { get { return CreateCommand(Ok); } }
        private void Ok()
        {
            if (editing)
            {
                Data.EndEdit();
                editing = false;
            }
            ExecuteViewCommand(ViewCommands.Close);
        }

        [Display(Name = "Cancel",Order=2)]
        [ViewProperty(ButtonViewControl.Properties.Width, buttonWidth)]
        public ICommand CancelCommand { get { return CreateCommand(Cancel); } }
        private void Cancel()
        {
            if (editing)
            {
                Data.CancelEdit();
                editing = false;
            }
            ExecuteViewCommand(ViewCommands.Close);
        }

        public DataEditViewModel(T data)
        {
            Data = data;
        }

        #region IViewLayoutGeneratorProvider Members

        ViewLayoutItem IViewLayoutGeneratorProvider.Generate()
        {
            var generator = ServiceLocator.GetService<IViewLayoutGenerator>();
            var layout = generator.Generate(this, LayoutGenerateFlag.LayoutData | LayoutGenerateFlag.SkipLoadError);
            if (layout != null) return layout;
            layout = generator.Generate(this, LayoutGenerateFlag.TypeInfo);
            var attr = typeof(T).GetCustomAttributes(typeof(ViewAttribute), false).Cast<ViewAttribute>().FirstOrDefault();
            if (attr != null && attr.Title != null) layout.Caption = attr.Title; 
            return layout;
        }

        #endregion
    }
}
